<template>
  <dys-modal
    :open="open"
    :title="t('人员管理')"
    @cancel="emit('cancel')"
    @ok="handleSubmit"
    :width="400"
  >
    <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item :label="t('姓名')" v-bind="validateInfos.personName">
        <a-input
          v-model:value="modelRef.personName"
          :placeholder="t('请输入姓名')"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item :label="t('性别')" v-bind="validateInfos.personCode">
        <select-value-set
          v-model:value="modelRef.gender"
          value-set-code="GENDER"
          :placeholder="t('请选择性别')"
        ></select-value-set>
      </a-form-item>
    </a-form>
  </dys-modal>
</template>
<script lang="ts" setup>
import { pick } from "lodash";
import { useI18n } from "vue-i18n";
import { reactive, watch } from "vue";
import { Form, message } from "ant-design-vue";
import { add, update } from "@/api/system/person";
import type { PersonParams, QueryResult } from "@/api/system/person/typing";
import type { FormRule } from "@/typing";
import SelectValueSet from "@/components/select-value-set/index.vue";
interface Props {
  /**弹窗 */
  open: boolean;
  /**行数据 */
  model: QueryResult;
}
const props = defineProps<Props>();
const emit = defineEmits(["cancel", "ok"]);
const { t } = useI18n();
const initValue = (): PersonParams => ({
  personId: null,
  personName: null,
  gender: null,
});
const modelRef = reactive(initValue());
const modelRule = reactive<FormRule<PersonParams>>({
  personName: [{ required: true, message: () => t("请输入姓名") }],
  gender: [{ required: true, message: () => t("请选择性别") }],
});
const { validate, validateInfos, resetFields } = Form.useForm(
  modelRef,
  modelRule
);
watch([() => props.model, () => props.open], ([model]) => {
  resetFields(pick(model, Object.keys(modelRef)) || initValue());
});
/**提交 */
const handleSubmit = async () => {
  try {
    await validate();
  } catch {
    return message.warning(t("校验失败"));
  }
  const { success } = await (props.model?.personId ? update : add)(modelRef);
  if (success) {
    message.success(props.model?.personId ? t("修改成功") : t("新增成功"));
    emit("ok");
    emit("cancel");
  }
};
</script>
